<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增应用 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="createActions(record)"
          />
        </template>
      </template>
    </BasicTable>
    <AppDrawer @register="registerAppDrawer" @success="handleSuccess" />
    <AppDetailDrawer @register="registerAppDetailDrawer" @success="handleSuccess" />
    <CertificateDrawer @register="registerCertificateDrawer" @success="handleSuccess" />
    <CertificateDetailDrawer @register="registerCertificateDetailDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="tsx" setup>
  import { BasicTable, useTable, TableAction, ActionItem } from '@/components/Table';
  import { getConnectionList, changeConnectionState } from '@/api/connection';
  import { UpdateConnectionStateParams } from '@/api/model/connection';

  import { useDrawer } from '@/components/Drawer';
  import AppDrawer from './AppDrawer.vue';
  import AppDetailDrawer from './AppDetailDrawer.vue';
  import CertificateDrawer from '../components/CertificateDrawer/index.vue';
  import CertificateDetailDrawer from '../components/CertificateDetailDrawer/index.vue';
  import { searchFormSchema } from './data';

  import { connectionStateEnum, connectionStateMap } from '@/enums/connection'
  import { formatToDate } from '@/utils/dateUtil'
  import { BasicColumn } from '@/components/Table';
  import { Button } from '@/components/Button';
  import { downloadByUrl } from '@/utils/file/download';
  import { partnerTypeEnum } from '@/enums/partner';

  const columns: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: ['partner', 'name'],
      width: 150,
      ellipsis: false,
      customRender: ({ record }) => {
        return (
          <Button onClick={() => showAppDetail(record)} type="link">
            {() => record.partner.name}
          </Button>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 80,
      customRender: ({ record }) => {
        return connectionStateMap[record.state];
      },
    },
    {
      title: '类型',
      dataIndex: 'system_app_key',
      width: 80,
      customRender: ({ record }) => {
        return !!record.partner.system_app_key ? '内置应用': '第三方应用';
      },
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      width: 100,
      customRender: ({ record }) => {
        if (record.start_time) {
          return formatToDate(record.start_time);
        }
        return '-'
      },
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      width: 100,
      customRender: ({ record }) => {
        if (record.end_time) {
          return formatToDate(record.end_time);
        }
        return '-'
      },
    },
    {
      title: '我方授权书',
      dataIndex: 'our_side_certificate',
      width: 180,
      align: 'left',
      customRender: ({ record }) => {
        const url = record.our_side_certificate?.url;
        const generateText = url ? '更换': '生成';

        const handleViewCertificate = () => {
          viewCertificate(record.our_side_certificate);
        }

        const handleDownload = () => {
          downloadCertificate(record);
        }

        const handleGenerate = () => {
          generateCertificate(record);
        }

        return (
          <div>
            <div style="display:inline-block;">{ url? '已生成': '未生成' }</div>
            <div onClick={handleViewCertificate} hidden={!url} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>查看</span></div>
            <div onClick={handleGenerate} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>{ generateText }</span></div>
            <div onClick={handleDownload} hidden={!url} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>下载</span></div>
          </div>
        )
      },
    },
    {
      title: '对方授权书',
      dataIndex: 'other_side_certificate',
      width: 100,
      align: 'left',
      customRender: ({ record }) => {
        const url = record.other_side_certificate?.url;
        const uploaded_text = url ? '已上传': '未上传';
        const handleViewCertificate = () => {
          viewCertificate(record.other_side_certificate);
        }
        return (
          <div>
            <div style="display:inline-block;">{ uploaded_text }</div>
            <div onClick={handleViewCertificate} hidden={!url} style="display:inline-block;margin-left:8px;cursor: pointer; color: #0960BD;"><span>查看</span></div>
        </div>
        )
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 100,
      customRender: ({ record }) => {
        return formatToDate(record.created_at);
      },
    },
  ];

  const [registerAppDrawer, { openDrawer: openAppDrawer }] = useDrawer();
  const [registerAppDetailDrawer, { openDrawer: openAppDetailDrawer }] = useDrawer();
  const [registerCertificateDrawer, { openDrawer: openCertificateDrawer }] = useDrawer();
  const [registerCertificateDetailDrawer, { openDrawer: openCertificateDetailDrawer }] = useDrawer();

  const searchInfo = {
    type: partnerTypeEnum.APP,
  }

  const [registerTable, { reload }] = useTable({
    title: '应用互联',
    api: getConnectionList,
    columns,
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchema,
    },
    searchInfo: searchInfo,
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
      align: 'center',
    },
  });

  const createActions = (record) => {
    const switchText = record.state === connectionStateEnum.ONGOING ? '作废': '启用';
    const switchColor = record.state === connectionStateEnum.ONGOING ? 'error': 'success';
    const newState = record.state === connectionStateEnum.ONGOING ? connectionStateEnum.CANCELLED: connectionStateEnum.ONGOING;
    const actions: ActionItem[] = [
      {
        label: switchText,
        color: switchColor,
        popConfirm: {
          title: `确认${switchText}？`,
          confirm: () => {
            handleChangeState(record, newState);
          },
        },
      }
    ];
    return actions;
  };

  function showAppDetail(record: Recordable) {
    openAppDetailDrawer(true, {
      record,
    });
  }

  function handleCreate() {
    openAppDrawer(true, {
      isUpdate: false,
    });
  }

  function viewCertificate(record: Recordable) {
    openCertificateDetailDrawer(true, {
      record,
    });
  }

  async function handleChangeState(record: Recordable, state: string) {
    const params: UpdateConnectionStateParams = {
      state: state,
    }
    await changeConnectionState(record.id, params);
    reload();
  }

  function generateCertificate(record: Recordable) {
    openCertificateDrawer(true, {
      record,
    });
  }

  function downloadCertificate(record: Recordable) {
    downloadByUrl({
      url: record.our_side_certificate.url,
      target: '_self',
    });
  }

  function handleSuccess() {
    reload();
  }

</script>